// TODO 支持过期时间
export class WebStorage {
  private store
  constructor (store: Storage) {
    this.store = store
  }

  /**
   * @param key
   * @param def 返回 null 时的默认值
   */
  getItem<D = unknown> (key: string, def?: D) {
    let value = this.store.getItem(key)
    try {
      value = value && JSON.parse(value as string)
    } catch (e) {
      return value
    }

    return value ?? def ?? null
  }

  setItem (key: string, value: unknown) {
    if (value === undefined) return
    return this.store.setItem(key, JSON.stringify(value))
  }

  removeItem (key: string) {
    this.store.removeItem(key)
  }
}

export const session = new WebStorage(sessionStorage)
export const storage = new WebStorage(localStorage)
